import LeRoute from './le-route'
import LeUtils from './le-utils'
const ApiAuth = {

    loadConfig: function(guard) {
        return  LeRoute.quiet().request('api.l-e-s.auth.config', {guard: guard})
            .then(function (res_data) {
                return  LeUtils.valueGet(res_data, 'data', {});
            })
    },
    login :function (type,data) {
        let api = '';
        switch (type) {

            case "mobileLogin":
                api = 'api.l-e-s.auth.login.mobile';
                break;
            case "emailLogin":
                api = 'api.l-e-s.auth.login.email';
                break;

            case "accountLogin":
                api = 'api.l-e-s.auth.login';

                break;
            default:
                api = type
                break;

        }
        LeStorage.setClientSource();

        return LeRoute.request(api, data)
            .then(function (res_data) {
                let user = LeUtils.valueGet(res_data, 'data.user', null);
                let token = LeUtils.valueGet(res_data, 'data.token', null);
                if (user) {
                    LeStorage.saveAuthInfo(user, token)
                }
                return {user,token}
            })
    },
    checkLogin :function (guard) {
        return LeRoute.quiet().request('api.l-e-s.auth.logged', {guard: guard})
            .then(function (res_data) {
                let user = LeUtils.valueGet(res_data, 'data.user', null);
                let token = LeUtils.valueGet(res_data, 'data.token', null);
                if (user) {
                    LeStorage.saveAuthInfo(user, token)
                }else {
                    LeStorage.clearAuthInfo();
                    LeStorage.removeClientSource();
                }
                return {user,token}
            }).catch(function (error){
                LeStorage.clearAuthInfo();
                LeStorage.removeClientSource();
            });
    },
    logout :function (guard) {
        return LeRoute.request('api.l-e-s.auth.logout', {guard:guard})
            .then(function (res_data) {
                LeStorage.clearAuthInfo();
                LeStorage.removeClientSource();
                return res_data;
            })
    },
    register :function (data) {
        return  LeRoute.request('api.l-e-s.auth.register', data)
            .then(function (res_data) {
                return  LeUtils.valueGet(res_data, 'data', {});
            })
    }
}

export default ApiAuth
